package com.ji.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.ServletRegistration;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidConfig{
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource ();
    }
    //后台监控  web.xml
    //因为SpringBoot内置了Servlet容器所有没有web.xml，替代方法ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        //后台需要有人登录账号密码
        HashMap<String, String> initParams = new HashMap<> ();
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<> (new StatViewServlet (), "/druid/*");
        //增加配置
        initParams.put ("loginUsername","admin");  //登录key是固定的
        initParams.put ("loginPassword","123456");

        //允许谁可以访问
        initParams.put ("allow","");//""谁都可以访问
        //禁止谁能访问呢
        //initParams.put ("jsp","ip地址")
        bean.setInitParameters (initParams);//设置初始化参数
        return bean;
    }

    //filter 过滤器
    @Bean
    public FilterRegistrationBean webStartFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<> ();
        bean.setFilter (new WebStatFilter ());
        //可以过滤那些请求
        HashMap<String, String> initParams = new HashMap<> ();
        initParams.put ("exclusions","*.js,*.css,/druid/*");//这些东西不通行

        return bean;
    }
}
